﻿using System.Collections.Generic;
using System.Linq;

namespace Beeflys.Generator
{
    static class Messenger
    {
        private static List<Error> errors = new List<Error>();
        private static List<UTypeInfo> messenger = new List<UTypeInfo>();

        public static (List<UTypeInfo>, List<Error>) Start(List<UTypeInfo> source)
        {
            foreach (var typeInfo in source)
            {
                if (typeInfo.IsInterface) continue;
                if (typeInfo.BaseType.FullName != MessengerType.A_MESSENGER) continue;
                if (!typeInfo.IsSealed)
                {
                    errors.Add(new Error($"The type that inherits from {MessengerType.A_MESSENGER} must be A sealed class"));
                }
                
                var baseInterfaces = typeInfo.GetBaseInterfaces();
                
                var commonInterfaces = new List<UTypeInfo>();
                var messengerInterfaces = new List<UTypeInfo>();
                foreach (var item in baseInterfaces)
                {
                    var items = item.Attributes;
                    var list = items.Where(info => 
                    {
                        return (info.FullName == MessengerType.ACTOR_MESSENGER_DECLARE_ATTRIBUTE_NAME || info.FullName == MessengerType.ACTOR_MESSENGER_DECLARE_ATTRIBUTE_FULLNAME); 
                    }).ToList();

                    if (list.Count > 0)
                    {
                        messengerInterfaces.Add(item);
                    }
                    else
                    {
                        commonInterfaces.Add(item);
                    }
                }

                if (commonInterfaces.Count > 0)
                {
                    foreach (var item in commonInterfaces)
                    {
                        errors.Add(new Error($"A type {typeInfo.FullName} derived from {MessengerType.A_MESSENGER} does not implement {item.FullName}"));    
                    }
                }
                
                messenger.Add(typeInfo);
            }

            return (null, errors);
        }
    }
}